import { Message } from '@arco-design/web-vue';
import { useRouter } from 'vue-router';

import type { AppRouteRecordRaw } from '@/router/routes/types';
import { useAppStore, useUserStore } from '@/store';

export default function useUser() {
  const router = useRouter();
  const userStore = useUserStore();
  const appStore = useAppStore();

  const removeServerRoutes = (menus: AppRouteRecordRaw[]) => {
    if (menus) {
      menus.forEach((item) => {
        if (router.hasRoute(item.name as string)) {
          router.removeRoute(item.name as string);
        }
        if (item.children) {
          removeServerRoutes(item.children as AppRouteRecordRaw[]);
        }
      });
    }
  };

  const logout = async (logoutTo?: string, showMessage = true) => {
    removeServerRoutes(appStore.serverMenu);
    await userStore.logout();
    if (showMessage) Message.success('退出登录成功');
    const currentRoute = router.currentRoute.value;
    router.push({
      name: logoutTo && typeof logoutTo === 'string' ? logoutTo : 'login',
      query: {
        ...router.currentRoute.value.query,
        redirect: currentRoute.name as string,
      },
    });
  };
  return {
    logout,
  };
}
